import ScrollBarLayout from '@/components/ScrollBarLayout';
import Cls from 'classnames';
import { DescriptionsType } from '@/components/DescriptionsType';
import { useContext, useMemo } from 'react';
import { ConractControllerContext } from '../common';
import { contractInfoEffect, getDescrConfig, ntkoQueryParams } from '../mconfig';
import { wordHandChildParam, getLoadMapList, getTenantID, getSelectDataMapList, renderTableTextNotColor, getFileNameByPath, getKeyRouter } from '@/utils';
import { NtkoPlugin } from '@/common/NtkoPluginType';
import { getBaseUrl } from '@/services/urlconst';
import { TypographyTitle } from '@/components/Typography/TypographyTitle';
import { useDescriptions, Descriptions } from '@/components/Descriptions';
import { ILoadMapTypeAll } from '@/common';
import { Form, TreeSelect } from 'antd';
import { EyeOutlined } from '@ant-design/icons';
import { history } from 'umi';

export const DetailInfoCenterViewMainOA: React.FC = () => {
  /** 获取上下文 */
  const { styleFixCls, curRes, contractDetailInfo, contractForm, readReadShowFileRun, locationProps } = useContext(ConractControllerContext);

  /** 引入在线预览 */
  const ntkoBrowser = useMemo(() => {
    const { ntkoBrowser } = NtkoPlugin(() => {});
    return ntkoBrowser;
  }, []);

  /** 点击在线预览文件 */
  const onNtkoReadWord = (urlName: string, urlObj: Record<string, any>, onlyRead?: boolean) => {
    const { ntkoWordUrl } = ntkoQueryParams(urlObj, curRes, urlName, onlyRead);

    const childStr = wordHandChildParam(urlObj);

    const extensBool = ntkoBrowser.ExtensionInstalled();
    if (extensBool) {
      ntkoBrowser?.openWindow(ntkoWordUrl, false, '', childStr);
    }
  };

  /**轻阅读预览 */
  const onOpenReadOfdWord = (fieldUrl: string) => {
    readReadShowFileRun({ fieldPath: `${getBaseUrl()}${fieldUrl}` });
  };

  /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.PAYMENT_STYLE}`, //支付方式
    `${getTenantID()}${ILoadMapTypeAll.COMPANY_TAXRATE}`, //税率
    `${getTenantID()}${ILoadMapTypeAll.CONTRACT_FIELDTYPE}`, //合同附件类型
    // `${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`, //量化单位
    `${getTenantID()}${ILoadMapTypeAll.CONTRACT_TYPE}`, // 合同类型
    `${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}`, // 合同状态
    `${getTenantID()}${ILoadMapTypeAll.PURCHASE_METHOD}`,
    `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}`, //供货类别
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`, //量化单位
    // `${getTenantID()}${ILoadMapTypeAll.MATERIAL_BRAND}`, //品牌
    `${getTenantID()}${ILoadMapTypeAll.CONTRACT_CURRENCYTYPE}`, //币种
  ]);

  /** 合同类型 */
  const businessTypeList = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.CONTRACT_TYPE}`], 'name', 'id', true);

  /** 初始化数据 */
  contractInfoEffect(contractDetailInfo, contractForm);

  /** 获取表单配置 */
  const { config } = getDescrConfig({
    openApplyModal: () => {},
    openTempModalFunc: () => {},
    openSubjectModal: () => {},
    changeTextInfo: {},
    onFormChange: () => {},
    onNtkoReadWord,
    openCounterpartModal: () => {},
    setOpenMaterialModal: () => {},
    // setOpenOwnerDeptModal: () => {},
    onOpenReadOfdWord,
    enterPurchProject: () => {},
  });

  //打开原合同详情
  const openContractDetail = () => {
    history.push({
      pathname: `/contractController/getMcontractByID/:${getKeyRouter()}${getKeyRouter()}`,
      state: {
        pageType: 'detail',
        id: contractDetailInfo?.id,
        pageInfo: contractDetailInfo,
        pIDDetailInfo: {
          ...contractDetailInfo,
        },
        returnPathName: locationProps?.pathname,
      },
    });
  };

  // 表格表单配置信息
  const [BasicConfig] = useDescriptions({
    labelWidth: 200,
    basicForm: contractForm,
    schemas: [
      {
        label: '申请日期',
        field: 'createTime',
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
      {
        label: '申请部门/单位',
        field: 'createDepartmentName',
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
      {
        label: '申请人',
        field: 'contactName',
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
      {
        label: '联系电话',
        field: 'phoneMobile',
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
    ],
  });

  // 表格表单配置信息
  const [ReConfig] = useDescriptions({
    labelWidth: 200,
    basicForm: contractForm,
    schemas: [
      {
        field: `contractName`,
        label: `合同名称`,
        component: 'InputTextArea',
        placeholder: '--',
        disabled: true,
        autoSize: { minRows: 1, maxRows: 3 },
        contentAfter: (
          <a onClick={openContractDetail}>
            <EyeOutlined />
          </a>
        ),
      },
      {
        field: `contractCode`,
        label: `合同编号`,
        component: 'Input',
        disabled: true,
      },
      {
        field: `capitalDirStr`,
        label: `资金流向`,
        component: 'Input',
        disabled: true,
      },
      {
        field: `contractNum`,
        label: `合同份数`,
        component: 'InputNumber',
        placeholder: '--',
        disabled: true,
        contentAfter: '份',
      },
      {
        field: `sumInTax`,
        label: `合同金额`,
        component: 'InputNumber',
        placeholder: '--',
        disabled: true,
        contentAfter: '元',
      },
      {
        field: `currencyType`,
        label: `币种`,
        component: 'Select',
        disabled: true,
        showArrow: false,
        options: loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.CONTRACT_CURRENCYTYPE}`],
        fieldNames: {
          label: 'name',
          value: 'id',
        },
      },
      {
        field: `businessType`,
        label: `合同类型`,
        component: 'Render',
        options: businessTypeList,
        render: (text) => {
          return (
            <TreeSelect
              loading={mapLoading}
              disabled={true}
              showArrow={false}
              placeholder="请选择"
              treeData={businessTypeList}
              fieldNames={{
                label: 'name',
                value: 'value',
                children: 'children',
              }}
              showSearch={true}
              treeNodeFilterProp={'name'}
              onSelect={(_value, node) => {
                if (node?.pID) {
                  contractForm?.setFieldsValue({
                    pbusinessType: node?.pID,
                    // 合同类型上级
                    // draftCode: str,
                    // contractCode: str,
                    contractTypeCode: node?.shortCode,
                  });
                  // }
                }
              }}
            />
          );
        },
      },
      {
        field: `majorFlag`,
        label: `是否重大（要）合同`,
        component: 'Render',
        initialValue: 0,
        render: (text) => {
          return (
            <Form.Item name="majorFlag" style={{ cursor: 'not-allowed' }}>
              {renderTableTextNotColor(text)}
            </Form.Item>
          );
        },
      },
      {
        field: `projectName`,
        label: `预算项目名称`,
        component: 'Input',
        placeholder: '--',
        disabled: true,
      },
      {
        field: `projectCode`,
        label: `预算项目编号`,
        component: 'Input',
        placeholder: '--',
        disabled: true,
      },
      {
        field: `purchProjectName`,
        label: `采购项目名称`,
        component: 'Input',
        disabled: true,
        placeholder: '--',
      },
      {
        field: `procureRealName`,
        label: `采购方式`,
        component: 'Input',
        disabled: true,
        placeholder: '--',
      },
      {
        field: `oppositeListStr`,
        label: `相对方名称`,
        component: 'InputTextArea',
        colSpan: 2,
        disabled: true,
        autoSize: { minRows: 1, maxRows: 8 },
      },
      {
        field: `contractURL`,
        label: `合同文本`,
        component: 'Render',
        colSpan: 2,
        slotRender: (text: any) => {
          const contractName = text ? getFileNameByPath(text) : '';
          return (
            <div style={{ width: '100%', display: 'flex', justifyContent: 'space-between', padding: 10 }}>
              {contractName ? (
                <>
                  <a>{contractName}</a>
                  <a
                    onClick={() => {
                      onOpenReadOfdWord(contractDetailInfo?.contractURL);
                    }}
                  >
                    <EyeOutlined />
                  </a>
                </>
              ) : (
                <span>--</span>
              )}
            </div>
          );
        },
      },
      {
        field: `contractInfo`,
        label: `合同简介`,
        component: 'InputTextArea',
        placeholder: '--',
        colSpan: 2,
        showCount: true,
        disabled: true,
        autoSize: { minRows: 4, maxRows: 8 },
      },
    ],
  });

  return (
    <>
      <div className="commonTabsBodyDom">
        <div className={Cls('tabsBodyInfoDom', `${styleFixCls}updateFormBox`)}>
          <ScrollBarLayout style={{ padding: '5px 100px' }}>
            {/* <div className={`${styleFixCls}infoViewOA-centerBodyTitleBox`}>合同申请</div> */}
            <TypographyTitle children={'合同会签申请'} style={{ textAlign: 'center', borderLeft: 'none' }} level={3} />
            <TypographyTitle children={'基本信息'} style={{ margin: '15px 0' }} />
            <Descriptions config={BasicConfig} />
            <TypographyTitle children={'合同信息'} style={{ margin: '15px 0' }} />
            <Descriptions config={ReConfig} />
            {/* <DescriptionsType config={config} titleType={true} /> */}
          </ScrollBarLayout>
        </div>
      </div>
    </>
  );
};
